package com.sx.pipeline.ui.needs.construction

import android.app.Application
import android.text.TextUtils
import com.alibaba.android.arouter.launcher.ARouter
import com.amap.api.services.core.PoiItem
import com.blankj.utilcode.util.ToastUtils
import com.sx.mvvmlibs.base.BaseViewModel
import com.sx.mvvmlibs.bus.RxBus
import com.sx.mvvmlibs.event.SingleLiveEvent
import com.sx.mvvmlibs.http.CommonObserver
import com.sx.mvvmlibs.utils.Logs
import com.sx.mvvmlibs.utils.RxThreadHelper
import com.sx.pipeline.R
import com.sx.pipeline.app.config.ReleaseNeedsType
import com.sx.pipeline.app.config.ReleaseTaskType
import com.sx.pipeline.app.event.BusEvent
import com.sx.pipeline.app.event.EventTypes
import com.sx.pipeline.app.model.CYBaseViewModel
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.repos.http.req.*
import com.sx.pipeline.repos.http.res.*
import com.sx.pipeline.ui.task.entity.ReleaseTaskListVO
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers

/**
 * @Author: YY
 * @Date: 2022/4/13
 * @Description: TODO
 */
class ConstructionNeedsVM(app: Application) : CYBaseViewModel(app) {

    /**
     * 获取我发布的任务类型标题
     */
    fun getReleaseTabsList(): List<String> {
        val tabs = mutableListOf<String>()
        tabs.add(getApplication<Application>().getString(R.string.txt_pending_review))
        tabs.add(getApplication<Application>().getString(R.string.txt_be_quoted))
        tabs.add(getApplication<Application>().getString(R.string.txt_quoted))
        tabs.add(getApplication<Application>().getString(R.string.txt_cancelled))
        tabs.add(getApplication<Application>().getString(R.string.txt_expired))
        tabs.add(getApplication<Application>().getString(R.string.txt_rejected))
        return tabs
    }


    /**
     * 获取我发布的需求类型id
     */
    fun getReleaseNeedsTabsId(): List<Int> {
        val tabs = mutableListOf<Int>()
        tabs.add(ReleaseNeedsType.PENDING_REVIEW.code)
        tabs.add(ReleaseNeedsType.TO_BE_QUOTED.code)
        tabs.add(ReleaseNeedsType.QUOTED.code)
        tabs.add(ReleaseNeedsType.CANCELLED.code)
        tabs.add(ReleaseNeedsType.EXPIRED.code)
        tabs.add(ReleaseNeedsType.REJECTED.code)
        return tabs
    }

    //地图页面拿到的位置数据
    val locationEvent: SingleLiveEvent<PoiItem> = SingleLiveEvent()
    override fun registerRxBus() {
        addSubscribe(
            RxBus.getDefault().toObservable(BusEvent::class.java)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    when (it.type) {
                        EventTypes.SELECT_SITE.code -> {
                            val poiItem: PoiItem = it.data as PoiItem
                            locationEvent.postValue(poiItem)
                            Logs.d("选择的地点：${poiItem.provinceName} === ${poiItem.cityName} === ${poiItem.adName}===${poiItem.title}===${poiItem.snippet} ")
                            Logs.d("选择的地点：${poiItem.latLonPoint.latitude} === ${poiItem.latLonPoint.longitude}")
                        }
                    }
                }
        )
    }

    /**
     * 获取需求配置数据
     */
    val taskListEvent: SingleLiveEvent<TaskConfigVo> = SingleLiveEvent()

    //需求标题
    val needTitleData: MutableList<String> = ArrayList()

    //需求类型
    val needTypeData: MutableList<String> = ArrayList()

    //计量单位
    val needUnitData: MutableList<String> = ArrayList()

    //任务性质
    val needNatureData: MutableList<String> = ArrayList()

    //结算方式
    val settleMethodData: MutableList<String> = ArrayList()
    fun getNeed() {
        addSubscribe(
            mModel.getNeed()
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<TaskConfigVo, BaseViewModel<*>>
                    (this, true) {

                    override fun onResult(result: TaskConfigVo) {
                        taskListEvent.postValue(result)
                        for (data in result.NEED_TITLE) {
                            needTitleData?.add(data.name)
                        }
                        for (data in result.TYPE_OF_REQUIREMENT) {
                            needTypeData?.add(data.name)
                        }
                        for (data in result.UNIT_OF_MEASUREMENT) {
                            needUnitData?.add(data.name)
                        }
                        for (data in result.NEED_LIVE_SITUATION) {
                            needNatureData?.add(data.name)
                        }
                        for (data in result.SETTLEMENT_METHOD) {
                            settleMethodData?.add(data.name)
                        }
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort("$msg")

                    }
                })
        )
    }


    /**
     * 施工单位 发布需求
     */
    fun addConstructionNeedOrder(
        title: String, //标题
        description: String, //描述
        name: String, //项目名称
        needType: String, //需求类型
        quantity: String, //需求量
        unit: String, //计量单位
        longitude: String, //经度
        latitude: String, //纬度
        addressDetail: String, //详细地址
        nature: String, //任务性质
        startDate: String, //开始时间
        endDate: String, //结束时间
        paymentMethod: String, //结算方式
        contact: String,
        contactPhone: String,
        appendixUrl: String, //附件
        payword:String
    ) {

        if (TextUtils.isEmpty(title)) {
            ToastUtils.showShort("请选择标题")
            return
        }
        if (TextUtils.isEmpty(name)) {
            ToastUtils.showShort("请输入项目名称")
            return
        }
        if (TextUtils.isEmpty(needType)) {
            ToastUtils.showShort("请选择需求类型")
            return
        }
        if (TextUtils.isEmpty(quantity)) {
            ToastUtils.showShort("请填写需求量")
            return
        }
        if (TextUtils.isEmpty(unit)) {
            ToastUtils.showShort("请选择计量单位")
            return
        }
        if (TextUtils.isEmpty(addressDetail) && TextUtils.isEmpty(longitude) && TextUtils.isEmpty(
                latitude
            )
        ) {
            ToastUtils.showShort("请选择需求服务地点")
            return
        }
        if (TextUtils.isEmpty(nature)) {
            ToastUtils.showShort("请选择任务性质")
            return
        }
        if (TextUtils.isEmpty(startDate)) {
            ToastUtils.showShort("请选择开始时间")
            return
        }
        if (TextUtils.isEmpty(endDate)) {
            ToastUtils.showShort("请选择结束时间")
            return
        }
        if (TextUtils.isEmpty(paymentMethod)) {
            ToastUtils.showShort("请选择结算方式")
            return
        }
        if (TextUtils.isEmpty(contact)) {
            ToastUtils.showShort("请选择联系人")
            return
        }
        if (TextUtils.isEmpty(contactPhone)) {
            ToastUtils.showShort("请填写联系电话")
            return
        }
        val service= OmsNeedServeDTO(0,quantity, unit, startDate, endDate, nature, paymentMethod, appendixUrl)

        val dto = ReleaseNeedsAddDTO(0,2,
            title,name, description, needType, 0,0,0,longitude, latitude, addressDetail,"",null,null,service,
            contact,contactPhone,payword
        )
        addSubscribe(
            mModel.addConstructionNeedOrder(dto)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Any, BaseViewModel<*>>
                    (this, true) {

                    override fun onResult(result: Any) {
                        ToastUtils.showShort("需求发布完成")
                        ARouter.getInstance().build(RoutePath.Mine.RELEASE_RESULT).navigation()
                        finish()
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort("$msg")
                    }
                })
        )
    }


    /**
     * 施工单位 发布需求
     */
    fun editConstructionNeedOrder(
        id: Int,
        serviceId:Int,
        title: String, //标题
        description: String, //描述
        name: String, //项目名称
        needType: String, //需求类型
        quantity: String, //需求量
        unit: String, //计量单位
        longitude: String, //经度
        latitude: String, //纬度
        addressDetail: String, //详细地址
        nature: String, //任务性质
        startDate: String, //开始时间
        endDate: String, //结束时间
        paymentMethod: String, //结算方式
        contact: String,
        contactPhone: String,
        appendixUrl: String, //附件
    ) {

        if (TextUtils.isEmpty(title)) {
            ToastUtils.showShort("请选择标题")
            return
        }
        if (TextUtils.isEmpty(name)) {
            ToastUtils.showShort("请输入项目名称")
            return
        }
        if (TextUtils.isEmpty(needType)) {
            ToastUtils.showShort("请选择需求类型")
            return
        }
        if (TextUtils.isEmpty(quantity)) {
            ToastUtils.showShort("请填写需求量")
            return
        }
        if (TextUtils.isEmpty(unit)) {
            ToastUtils.showShort("请选择计量单位")
            return
        }
        if (TextUtils.isEmpty(addressDetail) && TextUtils.isEmpty(longitude) && TextUtils.isEmpty(
                latitude
            )
        ) {
            ToastUtils.showShort("请选择需求服务地点")
            return
        }
        if (TextUtils.isEmpty(nature)) {
            ToastUtils.showShort("请选择任务性质")
            return
        }
        if (TextUtils.isEmpty(startDate)) {
            ToastUtils.showShort("请选择开始时间")
            return
        }
        if (TextUtils.isEmpty(endDate)) {
            ToastUtils.showShort("请选择结束时间")
            return
        }
        if (TextUtils.isEmpty(paymentMethod)) {
            ToastUtils.showShort("请选择结算方式")
            return
        }
        if (TextUtils.isEmpty(contact)) {
            ToastUtils.showShort("请选择联系人")
            return
        }
        if (TextUtils.isEmpty(contactPhone)) {
            ToastUtils.showShort("请填写联系电话")
            return
        }
        val service= OmsNeedServeDTO(serviceId,quantity, unit, startDate, endDate, nature, paymentMethod, appendixUrl)

        val dto = ReleaseNeedsAddDTO(id,2,
            title,name, description, needType, 0,0,0,longitude, latitude, addressDetail,"",null,null,service,
            contact,contactPhone
        )
        addSubscribe(
            mModel.editConstructionNeedOrder(dto)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Any, BaseViewModel<*>>
                    (this, true) {

                    override fun onResult(result: Any) {
                        ToastUtils.showShort("重新提交完成")
                        ARouter.getInstance().build(RoutePath.Mine.RELEASE_RESULT).navigation()
                        finish()
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort("$msg")
                    }
                })
        )
    }



    /**
     * 获取我参与的需求列表
     */
    var mPage = 1
    val releaseNeedsListEvent: SingleLiveEvent<Ipage<ReleaseNeedsVO>> = SingleLiveEvent()
    fun pushNeedPageList(status:Int,page: Int = 1) {
        addSubscribe(
            mModel.pushNeedPageList(status,page)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Ipage<ReleaseNeedsVO>, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: Ipage<ReleaseNeedsVO>) {
                        releaseNeedsListEvent.postValue(result)
                        mUI.initRefreshEvent().postValue(true)
                        if (page != 1) {
                            mUI.initLoadEvent().postValue(true)
                        }
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                        mUI.initRefreshEvent().postValue(false)
                        if (page != 1) {
                            mUI.initLoadEvent().postValue(true)
                        }
                    }
                })
        )
    }


    /**
     * 取消需求
     */
    val successNeedEvent: SingleLiveEvent<Boolean> = SingleLiveEvent()
    fun cancelNeedOrder(id: Int) {
        addSubscribe(
            mModel.cancelNeedOrder(id)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Any, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: Any) {
                        ToastUtils.showShort("取消成功")
                        successNeedEvent.postValue(true)
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                    }
                })
        )
    }

    /**
     * 删除需求
     */
    fun deleteNeedOrder(id: Int) {
        addSubscribe(
            mModel.deleteNeedOrder(id)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Any, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: Any) {
                        ToastUtils.showShort("删除成功")
                        successNeedEvent.postValue(true)
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                    }
                })
        )
    }

    /**
     * 需求详情
     */
    val needOrderDetailEvent: SingleLiveEvent<ReleaseNeedsVO> = SingleLiveEvent()
    fun getNeedOrderDetail(id: Int) {
        addSubscribe(
            mModel.getNeedOrderDetail(id)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<ReleaseNeedsVO, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: ReleaseNeedsVO) {
                        needOrderDetailEvent.postValue(result)
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                    }
                })
        )
    }

    /**
     * 报价列表
     */
    val viewQuotedListEvent: SingleLiveEvent<List<NeedsQuotedVO>> = SingleLiveEvent()
    fun getQuotedPrice(orderId: Int) {
        addSubscribe(
            mModel.getQuotedPrice(orderId)
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<List<NeedsQuotedVO>, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: List<NeedsQuotedVO>) {
                        viewQuotedListEvent.postValue(result)
                        dismissLoadingDialog()
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        dismissLoadingDialog()
                        ToastUtils.showShort(msg)
                    }
                })
        )
    }

    val needPriceEvent: SingleLiveEvent<Double> = SingleLiveEvent()
    fun getNeedPrice() {
        addSubscribe(
            mModel.getNeedPrice()
                .compose(RxThreadHelper.rxSchedulerHelper())
                .subscribeWith(object : CommonObserver<Double, BaseViewModel<*>>
                    (this, true) {
                    override fun onResult(result: Double) {
                        needPriceEvent.postValue(result)
                    }

                    override fun onFailed(code: Int, msg: String?) {
                        super.onFailed(code, msg)
                        ToastUtils.showShort(msg)
                    }
                })
        )
    }
}